package com.aca.market.service.impl;

import com.aca.market.entity.Permission;
import com.aca.market.entity.RolePerm;
import com.aca.market.entity.User;
import com.aca.market.mapper.PermissionMapper;
import com.aca.market.mapper.RolePermMapper;
import com.aca.market.service.IPermissionService;
import com.aca.market.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aca
 * @since 2020-11-13
 */
@Service
@Slf4j
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Autowired
    RolePermMapper rolePermMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    IUserService userService;


    @Override
    public List<String> getPerms(Long roleId) {
        List<String> allPerms = Collections.EMPTY_LIST;

        //用role_id去拿role_perm的perm_id集合
        List<Long> permsId = rolePermMapper.selectList(new QueryWrapper<RolePerm>()
                .eq("role_id", roleId))
                .parallelStream()
                .map(p -> p.getPermissionId())
                .collect(Collectors.toList());

        if (permsId == null || permsId.isEmpty()){
            return Collections.emptyList();
        }

        //再用perm_id集合去perm里拿权限
        allPerms = permissionMapper.selectList(new QueryWrapper<Permission>()
                .in("id",permsId))
                .parallelStream()
                .map((permission -> permission.getPermission()))
                .collect(Collectors.toList());
        log.info("++++++roleId:"+roleId+"================拿到权限"+allPerms.toString());

        return allPerms;
    }

    @Override
    public List<Permission> getPermsEntity(Long roleId) {
        //用role_id去拿role_perm的perm_id集合
        List<Long> permsId = rolePermMapper.selectList(new QueryWrapper<RolePerm>()
                .eq("role_id", roleId))
                .parallelStream()
                .map(p -> p.getPermissionId())
                .collect(Collectors.toList());

        if (permsId == null || permsId.isEmpty()){
            return Collections.emptyList();
        }

        //再用perm_id集合去perm里拿权限
        return permissionMapper.selectList(new QueryWrapper<Permission>()
                .in("id",permsId));
    }

    @Override
    public List<Long> getPermsId(Long roleId) {
        //用role_id去拿role_perm的perm_id集合
        List<Long> permsId = rolePermMapper.selectList(new QueryWrapper<RolePerm>()
                .eq("role_id", roleId))
                .parallelStream()
                .map(p -> p.getPermissionId())
                .collect(Collectors.toList());

        if (permsId == null || permsId.isEmpty()){
            return Collections.emptyList();
        }

        //再用perm_id集合去perm里拿权限
        return permissionMapper.selectList(new QueryWrapper<Permission>()
                .in("id",permsId)).parallelStream().mapToLong((p)->p.getId()).boxed().collect(Collectors.toList());
    }

    @Override
    //roles: indent,item....
    public List<String> getUserRoles(Long userId) {
        List<String> perms = getPerms(userId);
        Set<String> set = new HashSet<>();
        for (String perm : perms) {
            String role = perm.split(":")[0];
            if(!set.contains(role)){
                set.add(role);
                log.info("====================getRole " + role);
            }
        }
        return set.parallelStream().collect(Collectors.toCollection(ArrayList::new));
    }

    @Override
    public List<String> getUserRoles(List<String> perms) {
        Set<String> set = new HashSet<>();
        for (String perm : perms) {
            String role = perm.split(":")[0];
            if(!set.contains(role)){
                set.add(role);
                log.info("====================getRole " + role);
            }
        }
        return set.parallelStream().collect(Collectors.toCollection(ArrayList::new));
    }


    @Override
    public boolean hasPermToDashBoard(){
        User nowUser = userService.nowUser();
        if (nowUser == null) return false;
        boolean[] hasRoles = SecurityUtils.getSubject().hasRoles(getUserRoles(nowUser.getRoleId()));
        boolean verified = false;
        for (boolean hasRole : hasRoles) {
            verified |= hasRole;
        }
        log.info("==========hasPermToDashBoard : " +verified + Arrays.toString(hasRoles));
        return verified;
    }
}
